import pkg from 'fs-extra';
const {readdirSync, readFileSync, statSync, writeFileSync} = pkg;
import {RubbishJSObfuscator} from "./RubbishJSObfuscator.js";

function walk(path, callback) {
    const files = readdirSync(path);
    files.forEach((file) => {
        if (statSync(path+"/"+ file).isFile()) {
            callback(path + "/" + file);
        }
        else {
            walk(path + "/" + file, callback)
        }
    })
}

export function obFile(path) {
    if (path.indexOf("cocos-js") !== -1) {
        return;
    }
    if (path.indexOf("Utility") !== -1) {
        return;
    }
    if (path.indexOf("engine-adapter.js") !== -1) {
        return;
    }
    if (path.indexOf("web-adapter.js") !== -1) {
        return;
    }
    console.log("obFile " + path);


    let code = readFileSync(path, {encoding: "utf-8"})

    let jsObfuscator = new RubbishJSObfuscator(code);

    jsObfuscator.dot2String();
// jsObfuscator.generateCode();
    jsObfuscator.processString();
    jsObfuscator.uglifyJSMinify();

    let dest = path.replace("wechatgame-back", "wechatgame")
    writeFileSync(dest, jsObfuscator.code);
}


export function ob(path) {

    walk(path, (filePath) => {
        if (! filePath.endsWith(".js")){
            return
        }
        obFile(filePath);
    })

}